#include "Common.h"

GameObject::GameObject(ui64 guid) : m_isstatic(false), m_loaded(false)
{
	m_guid.Init(guid);
	m_ui32values = _fields;
	m_fieldcount = GAMEOBJECT_END;
	m_updatemask.SetCount(GAMEOBJECT_END);
	memset(m_ui32values, NULL, 4 * GAMEOBJECT_END);
	SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
	SetUI64Value(OBJECT_FIELD_GUID, guid);
	m_typeid = TYPEID_GAMEOBJECT;
	SetUI32Value(OBJECT_FIELD_TYPE, 32 | 1);
}

void GameObject::Load(ui32 entry)
{
	m_info = miscmgr->GetGameObjectInfo(entry);
	if(!m_info)
		return;
	SetUI32Value(OBJECT_FIELD_ENTRY, entry);
	SetUI32Value(GAMEOBJECT_DISPLAYID, m_info->displayid);
	SetByte(GAMEOBJECT_BYTES_1, 3, 0);
	SetByte(GAMEOBJECT_BYTES_1, 0, 769);
	SetByte(GAMEOBJECT_BYTES_1, 1, m_info->type);
	SetUI32Value(GAMEOBJECT_FLAGS, 0);
	m_loaded = true;
}

void GameObject::Spawn(float x, float y, float z, ui32 mapid, float orientation, bool static_)
{
	if(!m_loaded)
		return;
	m_position._x = x;
	m_position._y = y;
	m_position._z = z;
	m_position._mapid = mapid;
	m_orientation = orientation;
	m_isstatic = static_;
	//SetFloatValue(GAMEOBJECT_FACING, orientation);
	if (orientation > (float)M_PI)
		orientation -= 2*(float)M_PI;
	else if (orientation < -(float)M_PI)
		orientation += 2*(float)M_PI;
	float sin = sinf(orientation / 2.f);

	if(sin >= 0)	
		orientation = 1.f + 0.125f * sin;
	else
		orientation = 1.25f + 0.125f * sin;
	SetFloatValue(GAMEOBJECT_ROTATION, orientation);
	SetByte(GAMEOBJECT_BYTES_1, 0, 0);
	//SetFloatValue(GAMEOBJECT_POS_X, x);
	//SetFloatValue(GAMEOBJECT_POS_Y, y);
	//SetFloatValue(GAMEOBJECT_POS_Z, z);
	if(m_maphandler)
	{
		m_maphandler->AddObject(this);
		SetEventWorker(m_maphandler);
		//TimedEvent* te = new TimedEvent(new CallbackP0<GameObject>(&GameObject::CloseObject, this), 200, 0);
		//AddEvent(te);
	}
	if(GetByte(GAMEOBJECT_BYTES_1, 1) == GAMEOBJECT_TYPE_DOOR)
		CloseObject();
}

void GameObject::CloseObject()
{
	SetByte(GAMEOBJECT_BYTES_1, 0, 1);
	SetUI32Value(GAMEOBJECT_FLAGS, GetUI32Value(GAMEOBJECT_FLAGS) & ~1);
}